package com.zjdiepu.www.diepu.biz.impl;

import java.io.File;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;
import com.zjdiepu.www.diepu.biz.IQiniuProxySerive;
import com.zjdiepu.www.enums.TransferAttachStatus;
import com.zjdiepu.www.net.HttpClient;
import com.zjdiepu.www.proxy.biz.impl.BaseProxyService;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferOtherAttachments;
import com.zjdiepu.www.proxy.model.ext.transfer.TransferOtherAttachmentsExt;

/**
 * 文件操作
 * @author xiongxiaotun
 */
@Service
public class QiniuProxySeriveImpl extends BaseProxyService implements IQiniuProxySerive {
	public static final Logger logger = LoggerFactory.getLogger(QiniuProxySeriveImpl.class);
	//2小时
	private static final Integer URL_TIMEOUT = 3600;
	
	@Override
    public boolean downloadFile(String orderno) {
        TransferOtherAttachmentsExt transferOtherAttachmentsExt = new TransferOtherAttachmentsExt();
        transferOtherAttachmentsExt.setBaseWhere();
        transferOtherAttachmentsExt.setBankOrderNo(orderno);
        transferOtherAttachmentsExt.withOutPage();
        transferOtherAttachmentsExt.setTransferAttachStatus(TransferAttachStatus.WEI_XIA_ZAI.getCode());
		List<TransferOtherAttachments> transferOtherAttachments = transferOtherAttachmentsMapper.selectByExt(transferOtherAttachmentsExt);
		if(CollectionUtils.isEmpty(transferOtherAttachments)) {
			return true;
		}
		for(TransferOtherAttachments transferOtherAttachment : transferOtherAttachments) {
			if(transferOtherAttachment == null) {
				continue;
			}
			String fileName = transferOtherAttachment.getFileName();
			
			if(StringUtils.isBlank(fileName)) {
				continue;
			}
			
			if(!exists(fileName)) {
				continue;
			}
			
			String basePathNginx = fileProxyConfig.getBasePathNginx();
			String folder = fileProxyConfig.getBasePathNginx() + fileProxyConfig.getBasePathQiniu() + orderno;
			File file = new File(folder);
			if(!file.exists()) {
				file.mkdirs();
			}
			String localFilePath = folder + "/" + fileName;
			if(new File(localFilePath).exists()) {
				transferOtherAttachment.setLocalFilePath(localFilePath.substring(basePathNginx.length()));
				transferOtherAttachment.setTransferAttachStatus(TransferAttachStatus.YI_XIA_ZAI.getCode());
			} else {
				fileName = qiniuProperty.getGateway() + fileName;
				Auth auth = Auth.create(qiniuProperty.getAccessKey(), qiniuProperty.getSecretKey());
				String downLoadUrl = auth.privateDownloadUrl(fileName, URL_TIMEOUT);
				boolean thisdownloadFile = HttpClient.downloadFile(downLoadUrl, localFilePath);
				if(thisdownloadFile) {
					transferOtherAttachment.setLocalFilePath(localFilePath.substring(basePathNginx.length()));
					transferOtherAttachment.setTransferAttachStatus(TransferAttachStatus.YI_XIA_ZAI.getCode());
				}
			}
			transferOtherAttachmentsMapper.updateByPrimaryKeySelective(transferOtherAttachment);
		}
		return true;
    }
	
	@Override
    public boolean exists(String fileName) {
    	if(StringUtils.isBlank(fileName)) {
    		return false;
    	}
    	try {
    		BucketManager bucketManager = getBucketManager();
    		//只检查三个前缀
			FileListing listFiles = bucketManager.listFiles(qiniuProperty.getNewBucket(), fileName, "", 1, "");
			if(listFiles.items != null && listFiles.items.length > 0){
				for(FileInfo fileInfo : listFiles.items) {
					if(fileName.equals(fileInfo.key)) {
						return true;
					}
				}
			}
		} catch (QiniuException e) {
			logger.error("检查文件是否存在异常。fileName：{}, e : {}。",fileName, e);
		}
    	return false;
    }
	
	private BucketManager getBucketManager() {
        Auth auth = Auth.create(qiniuProperty.getAccessKey(), qiniuProperty.getSecretKey());
        Configuration cfg = new Configuration(Zone.zone0());
        return new BucketManager(auth, cfg);
    }
}
